// utils/audioManager.js - 全局音频管理器
class AudioManager {
  constructor() {
    if (AudioManager.instance) {
      return AudioManager.instance
    }
    
    // 音频上下文
    this.audioContext = null
    
    // 播放状态
    this.playState = {
      isPlaying: false,
      isPaused: false,
      isLoading: false,
      currentTime: 0,
      totalDuration: 0,
      progress: 0,
      volume: 50,
      playMode: 'list' // list: 列表循环, single: 单曲循环, random: 随机
    }
    
    // 当前音频信息
    this.currentAudio = {
      id: '',
      title: '未知音频',
      description: '',
      duration: '00:00',
      size: '',
      format: '',
      category: '',
      url: '',
      thumbnail: ''
    }
    
    // 播放列表
    this.playlist = []
    this.currentIndex = 0
    
    // 浮窗显示状态
    this.showFloatingPlayer = false
    
    // 事件监听器
    this.listeners = {
      stateChange: [],
      audioChange: [],
      playlistChange: []
    }
    
    // 进度计时器
    this.progressTimer = null
    
    // 初始化音频上下文
    this.initAudioContext()
    
    AudioManager.instance = this
  }
  
  /**
   * 获取单例实例
   */
  static getInstance() {
    if (!AudioManager.instance) {
      AudioManager.instance = new AudioManager()
    }
    return AudioManager.instance
  }
  
  /**
   * 初始化音频上下文
   */
  initAudioContext() {
    if (this.audioContext) {
      this.audioContext.destroy()
    }
    
    this.audioContext = wx.createInnerAudioContext()
    
    // 播放开始
    this.audioContext.onPlay(() => {
      console.log('全局音频开始播放')
      this.playState.isPlaying = true
      this.playState.isPaused = false
      this.playState.isLoading = false
      this.startProgressTimer()
      this.notifyStateChange()
    })
    
    // 播放暂停
    this.audioContext.onPause(() => {
      console.log('全局音频暂停')
      this.playState.isPlaying = false
      this.playState.isPaused = true
      this.stopProgressTimer()
      this.notifyStateChange()
    })
    
    // 播放停止
    this.audioContext.onStop(() => {
      console.log('全局音频停止')
      this.playState.isPlaying = false
      this.playState.isPaused = false
      this.playState.currentTime = 0
      this.playState.progress = 0
      this.stopProgressTimer()
      this.notifyStateChange()
    })
    
    // 播放结束
    this.audioContext.onEnded(() => {
      console.log('全局音频播放结束')
      this.handlePlayEnd()
    })
    
    // 播放错误
    this.audioContext.onError((res) => {
      console.error('全局音频播放错误:', res)
      this.playState.isLoading = false
      this.playState.isPlaying = false
      this.notifyStateChange()
    })
    
    // 音频加载中
    this.audioContext.onWaiting(() => {
      this.playState.isLoading = true
      this.notifyStateChange()
    })
    
    // 音频可以播放
    this.audioContext.onCanplay(() => {
      this.playState.isLoading = false
      this.playState.totalDuration = this.audioContext.duration || 0
      this.notifyStateChange()
    })
  }
  
  /**
   * 设置当前音频
   */
  setCurrentAudio(audioInfo) {
    this.currentAudio = { ...audioInfo }
    
    if (this.audioContext && audioInfo.url) {
      this.audioContext.src = audioInfo.url
      this.audioContext.title = audioInfo.title
    }
    
    this.notifyAudioChange()
  }
  
  /**
   * 设置播放列表
   */
  setPlaylist(playlist, currentIndex = 0) {
    this.playlist = [...playlist]
    this.currentIndex = Math.max(0, Math.min(currentIndex, playlist.length - 1))
    this.notifyPlaylistChange()
  }

  /**
   * 添加到播放列表
   */
  addToPlaylist(audioInfo) {
    // 检查是否已经在播放列表中
    const isAlreadyInPlaylist = this.playlist.some(item => item._id === audioInfo._id)
    
    if (isAlreadyInPlaylist) {
      return false // 已存在
    }
    
    this.playlist.push(audioInfo)
    this.notifyPlaylistChange()
    return true // 添加成功
  }

  /**
   * 从播放列表移除
   */
  removeFromPlaylist(index) {
    if (index >= 0 && index < this.playlist.length) {
      this.playlist.splice(index, 1)
      
      // 调整当前索引
      if (index < this.currentIndex) {
        this.currentIndex--
      } else if (index === this.currentIndex) {
        // 如果移除的是当前播放的音频
        if (this.playlist.length === 0) {
          // 列表为空，停止播放
          this.close()
          return
        } else {
          // 调整到合适的索引
          this.currentIndex = Math.min(this.currentIndex, this.playlist.length - 1)
          // 播放新的当前音频
          this.playAudioByIndex(this.currentIndex)
        }
      }
      
      this.notifyPlaylistChange()
      return true
    }
    return false
  }

  /**
   * 清空播放列表
   */
  clearPlaylist() {
    this.playlist = []
    this.currentIndex = 0
    this.close() // 停止播放
    this.notifyPlaylistChange()
  }
  
  /**
   * 播放/暂停切换
   */
  togglePlay() {
    if (!this.audioContext || !this.currentAudio.url) {
      return false
    }
    
    if (this.playState.isPlaying) {
      this.audioContext.pause()
    } else {
      this.audioContext.play()
    }
    return true
  }
  
  /**
   * 播放指定音频
   */
  async playAudio(audioInfo) {
    this.setCurrentAudio(audioInfo)
    
    if (this.audioContext) {
      this.audioContext.play()
    }
    
    // 显示浮窗
    this.showFloatingPlayer = true
    this.notifyStateChange()
  }
  
  /**
   * 上一首
   */
  playPrevious() {
    if (this.playlist.length === 0) return false
    
    const prevIndex = this.currentIndex > 0 ? this.currentIndex - 1 : this.playlist.length - 1
    return this.playAudioByIndex(prevIndex)
  }
  
  /**
   * 下一首
   */
  playNext() {
    if (this.playlist.length === 0) return false
    
    const nextIndex = this.currentIndex < this.playlist.length - 1 ? this.currentIndex + 1 : 0
    return this.playAudioByIndex(nextIndex)
  }
  
  /**
   * 根据索引播放音频
   */
  async playAudioByIndex(index) {
    if (index >= 0 && index < this.playlist.length) {
      this.currentIndex = index
      const audioInfo = this.playlist[index]
      
      // 如果需要从云端获取详细信息
      try {
        const res = await wx.cloud.callFunction({
          name: 'fetchAudio',
          data: {
            type: 'getAudioDetail',
            audioId: audioInfo._id
          }
        })
        
        if (res.result && res.result.success) {
          await this.playAudio(res.result.data)
          return true
        }
      } catch (error) {
        console.error('获取音频详情失败:', error)
      }
      
      // 如果获取失败，使用列表中的基本信息
      await this.playAudio(audioInfo)
      return true
    }
    return false
  }
  
  /**
   * 处理播放结束
   */
  handlePlayEnd() {
    switch (this.playState.playMode) {
      case 'single':
        // 单曲循环
        if (this.audioContext) {
          this.audioContext.seek(0)
          this.audioContext.play()
        }
        break
      case 'list':
        // 列表循环
        this.playNext()
        break
      case 'random':
        // 随机播放
        if (this.playlist.length > 0) {
          const randomIndex = Math.floor(Math.random() * this.playlist.length)
          this.playAudioByIndex(randomIndex)
        }
        break
    }
  }
  
  /**
   * 设置播放模式
   */
  setPlayMode(mode) {
    this.playState.playMode = mode
    this.notifyStateChange()
  }
  
  /**
   * 设置进度
   */
  seekTo(progress) {
    if (this.audioContext && this.playState.totalDuration > 0) {
      const seekTime = (progress / 100) * this.playState.totalDuration
      this.audioContext.seek(seekTime)
      this.playState.progress = progress
      this.playState.currentTime = seekTime
      this.notifyStateChange()
    }
  }
  
  /**
   * 设置音量
   */
  setVolume(volume) {
    this.playState.volume = volume
    if (this.audioContext) {
      this.audioContext.volume = volume / 100
    }
    this.notifyStateChange()
  }
  
  /**
   * 显示/隐藏浮窗
   */
  setFloatingPlayerVisible(visible) {
    this.showFloatingPlayer = visible
    this.notifyStateChange()
  }
  
  /**
   * 关闭播放器
   */
  close() {
    if (this.audioContext) {
      this.audioContext.stop()
    }
    this.showFloatingPlayer = false
    this.currentAudio = {
      id: '',
      title: '未知音频',
      description: '',
      duration: '00:00',
      size: '',
      format: '',
      category: '',
      url: '',
      thumbnail: ''
    }
    this.notifyStateChange()
    this.notifyAudioChange()
  }
  
  /**
   * 开始进度计时器
   */
  startProgressTimer() {
    this.stopProgressTimer()
    this.progressTimer = setInterval(() => {
      if (this.audioContext && this.playState.isPlaying) {
        const currentTime = this.audioContext.currentTime
        const totalDuration = this.audioContext.duration || this.playState.totalDuration
        const progress = totalDuration > 0 ? (currentTime / totalDuration) * 100 : 0
        
        this.playState.currentTime = currentTime
        this.playState.totalDuration = totalDuration
        this.playState.progress = progress
        
        this.notifyStateChange()
      }
    }, 1000)
  }
  
  /**
   * 停止进度计时器
   */
  stopProgressTimer() {
    if (this.progressTimer) {
      clearInterval(this.progressTimer)
      this.progressTimer = null
    }
  }
  
  /**
   * 销毁音频管理器
   */
  destroy() {
    this.stopProgressTimer()
    if (this.audioContext) {
      this.audioContext.destroy()
      this.audioContext = null
    }
    this.listeners = {
      stateChange: [],
      audioChange: [],
      playlistChange: []
    }
  }
  
  /**
   * 添加事件监听器
   */
  addEventListener(type, callback) {
    if (this.listeners[type]) {
      this.listeners[type].push(callback)
    }
  }
  
  /**
   * 移除事件监听器
   */
  removeEventListener(type, callback) {
    if (this.listeners[type]) {
      const index = this.listeners[type].indexOf(callback)
      if (index > -1) {
        this.listeners[type].splice(index, 1)
      }
    }
  }
  
  /**
   * 通知状态变化
   */
  notifyStateChange() {
    this.listeners.stateChange.forEach(callback => {
      try {
        callback(this.playState, this.showFloatingPlayer)
      } catch (error) {
        console.error('状态变化回调错误:', error)
      }
    })
  }
  
  /**
   * 通知音频变化
   */
  notifyAudioChange() {
    this.listeners.audioChange.forEach(callback => {
      try {
        callback(this.currentAudio)
      } catch (error) {
        console.error('音频变化回调错误:', error)
      }
    })
  }
  
  /**
   * 通知播放列表变化
   */
  notifyPlaylistChange() {
    this.listeners.playlistChange.forEach(callback => {
      try {
        callback(this.playlist, this.currentIndex)
      } catch (error) {
        console.error('播放列表变化回调错误:', error)
      }
    })
  }
  
  /**
   * 格式化时间
   */
  formatTime(seconds) {
    if (!seconds || isNaN(seconds)) return '00:00'
    
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  
  /**
   * 获取当前状态
   */
  getState() {
    return {
      playState: { ...this.playState },
      currentAudio: { ...this.currentAudio },
      playlist: [...this.playlist],
      currentIndex: this.currentIndex,
      showFloatingPlayer: this.showFloatingPlayer
    }
  }
}

// 导出单例实例
export default AudioManager.getInstance()
